<?php


require_once 'Operations/Operation.php';

/**
 * Performs a log in command.
 */
class RequestToken extends Operation {
	/**
	 * Performs a log in command.
	 */
	public function execute() {
		// Fetch username and password:
		Logger::log("RequestToken", "Logging in.");
		$username = HTTPHandler::getPostParam("Email");
		$password = HTTPHandler::getPostParam("Passwd");
		if (!$username or !$password) {
			throw new PCException("Missing username and/or password", 400);
		}
		
		// Prepare logData:
		$logData["username"] = $username;
		
		// Fetch user:
		$user = UserTable::getByUsername($username);
		if (!$user) {
			$logData["error"] = "Username not found";
			Database::logActivity("RequestToken", 0, "N/A", serialize($logData));
			throw new PCException("Username not found.", 403);
		} else if (!$user->checkPassword($password)) {
			$logData["error"] = "Invalid password";
			Database::logActivity("RequestToken", 0, "N/A", serialize($logData));
			throw new PCException("Invalid password.", 403);
		} else if (!$user->isAuthorized()) {
			$logData["error"] = "User is not authorized";
			Database::logActivity("RequestToken", 0, "N/A", serialize($logData));
			throw new PCException("User is not authorized.", 403);
		}
		
		// Fetch token if there is one:
		$token = $user->getToken(HTTPHandler::getIP());
		if (!$token) {
			// Generate token:
			$tokenFactory = new TokenFactory();
			$token = $tokenFactory->generate($user, HTTPHandler::getIP());
			if (!$token) {
				throw new PCException("Unable to generate token.", 500);
			}
		}
		
		// Display token:
		HTTPHandler::add("Auth=" . $token->getTokenString());
		Logger::log("RequestToken", "Token returned.");

		// Log activity:
		$logData["token"] = $token->getTokenString();
		Database::logActivity("RequestToken", 0, "N/A", serialize($logData));
	}
}
?>
